package biback.domain.customer

import biback.domain._
import biback.domain.common.{Calculator, TrnContext}
import biback.domain.product.ProductAlgebra
import biback.utils.RegistryAlgebra
import cats.Monad

// 销户
class AccountCloseService[F[_] : Monad]
(
  algebra: RegistryAlgebra[F] with PersonalAlgebra[F] with ProductAlgebra[F]
) extends DomainService[F, CloseAccountRequest, Unit] {

  import algebra._

  def run(ctx: TrnContext, rq: CloseAccountRequest): ErrOrNoneF = {
    for {
      s <- customer.foundCustomerProduct(rq.acctId, rq.subAcctNo)
      // a <- product.found(s.product.base.product)
      c <- product.foundIntPrice(s.product.code)
      u <- customer.getSubAcctBalanceChanges(rq.acctId, rq.subAcctNo, ctx.date)
      i <- product.listBaseInt(c.intKey, u.from, ctx.date)
      e <- settleInt(ctx, rq, s.cNo, Calculator.calcInt(c, i, u.changes, u.from, ctx.date))
    } yield e
  }

  def settleInt(ctx: TrnContext, rq: CloseAccountRequest, cNo: CustomerNo, intAmt: BiDec): ErrOrNoneF =
    if (intAmt > 0)
      for {
        p <- registry.refFor[PersonalEntity](cNo.value)
        e <- p.ask(CalcInterest(ctx, rq.acctId, rq.subAcctNo, intAmt))
      } yield e
    else resultF(())

  // 销户试算
  def closeTrail(): ErrOrNoneF = ???

  // 冻结
  def freeze(): ErrOrNoneF = ???

  // 解冻
  def unfreeze(): ErrOrNoneF = ???

  // 续冻
  def renewFrozen(): ErrOrNoneF = ???

  // 止付
  def stopPayment(): ErrOrNoneF = ???

  // 圈存
  def forLoad(): ErrOrNoneF = ???

  // 解止付
  def resumePayment(): ErrOrNoneF = ???

  // 解圈存
  def unForLoad(): ErrOrNoneF = ???
}

case class CloseAccountRequest
(
  acctId: AccountId,
  subAcctNo: SubAccountNo
)
